<?php

namespace App\Models\Site;

use App\Models\BasicModel;
use App\Repositories\DataStatus;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * App\Models\SiteCode
 *
 * @property int $id id
 * @property string|null $to 接收方
 * @property int|null $code 验证码
 * @property int|null $type 1=注册2=登录3=修改密码4=变更资料5=其他
 * @property \Illuminate\Support\Carbon|null $created_at 创建时间
 * @property \Illuminate\Support\Carbon|null $updated_at 更新时间
 * @property \Illuminate\Support\Carbon|null $deleted_at 删除时间
 * @property int|null $status 状态1=正常2=已使用
 * @method static \Illuminate\Database\Eloquent\Builder|SiteCode newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|SiteCode newQuery()
 * @method static \Illuminate\Database\Query\Builder|SiteCode onlyTrashed()
 * @method static \Illuminate\Database\Eloquent\Builder|SiteCode query()
 * @method static \Illuminate\Database\Eloquent\Builder|SiteCode whereCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|SiteCode whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|SiteCode whereDeletedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|SiteCode whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|SiteCode whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|SiteCode whereTo($value)
 * @method static \Illuminate\Database\Eloquent\Builder|SiteCode whereType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|SiteCode whereUpdatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|SiteCode withTrashed()
 * @method static \Illuminate\Database\Query\Builder|SiteCode withoutTrashed()
 * @mixin \Eloquent
 */
class SiteCode extends BasicModel
{
    use HasDateTimeFormatter;
    use SoftDeletes;

    protected $table = 'site_code';

    const CODE_REG = 1;
    const CODE_LOGIN = 2;
    const CODE_PASSWORD = 3;
    const CODE_CHANGE = 4;
    const SMS_OTHER = 5;


    /**
     * @param $to
     * @param $code
     * @param $type
     * @return SiteCode|\Illuminate\Database\Eloquent\Model
     */
    public function createCode($to, $code, $type)
    {
        $data['to'] = $to;
        $data['code'] = $code;
        $data['type'] = $type;
        return self::create($data);
    }


    /**
     * @param $to
     * @param $code
     * @param $type
     * @return SiteCode|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function checkCode($to, $code, $type)
    {
        $where['to'] = $to;
        $where['code'] = $code;
        $where['type'] = $type;
        $where['status'] = DataStatus::DATA_OK;
        return self::where($where)->where('created_at', '>', now()->subMinutes(5))->first();
    }
}
